from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from Applications.Gallery.models import Photo
from Django_Admin.settings import IMAGE_URL

# Create your views here.

# TODO 照片列表Json

class PhotoListAPI(View):

    def get(self, request):
        """处理GET请求业务逻辑"""
        # 通过django的view实现商品列表页
        json_list = []
        # 获取所有商品
        items = Photo.objects.all()
        if len(items) == 0:
            return JsonResponse({'status': 0})
        status = 1
        for item in items:
            json_dict = {}
            # 获取商品的每个字段，键值对形式
            if status == 1:
                status = 0
            elif status == 0:
                status = 1

            if item.intro == 'None':
                json_dict['intro'] = item.body[0:50]
            else:
                json_dict['intro'] = item.intro

            time = str(item.pub_time)[0:10]
            json_dict['time'] = time

            json_dict['id'] = str(item.id)
            json_dict['title'] = item.title

            json_dict['type'] = item.type
            json_dict['view'] = str(item.views)
            json_dict['like'] = str(item.like)
            json_dict['status'] = str(status)

            # 合成地址页面
            # href = VUE_URL + "Details/Photo/" + str(item.id)
            href = str(item.id)
            json_dict['url'] = href

            # 封面为avatar
            photo = item.photo
            photo_url =IMAGE_URL + str(photo)
            json_dict['photo'] = photo_url


            json_list.append(json_dict)
        # 将获取到的数据返回到 json中
        # 返回json，一定要指定类型content_type='application/json'
        return JsonResponse(json_list, safe=False)
        # return render(request, 'items-classify.html', context=json_list)

    def post(self, request):
        pass